import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';

import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';

import { urlConfigs } from './config';

import * as moment from 'moment';
declare const MD5;

@Injectable()
export class TaskService {
    constructor(private http: Http) { }

    // 任务 — 完善资料
    fillProfile(req: Object, openid: string): Promise<any> {
        let updateHeaders = new Headers();
        updateHeaders.append('openid', openid);
        updateHeaders.append('taskid', '014ec9d6310c4e90b5c01b04a2ef634e');
        return this.http.put(urlConfigs.memberUpdate + '?' + this.encrypt(openid), req, { headers: updateHeaders })
            .toPromise()
            .then(response => response.json().code)
            .catch(this.handleError);
    };

    // 处理请求出错
    handleError(error: any): Promise<any> {
        alert('程序请求出错');
        return Promise.reject(error.message || error);
    };

    // MD5加密处理encrypt
    encrypt(openid: string) {
        // 获取时间戳
        let timeUnix = moment().valueOf().toString(); 

        // 加密key
        let key = timeUnix.substring(0, 3) + timeUnix.substring(10); 

        // 数组形式缓存两个参数
        let paramString = ['openid=' + openid, 't=' + timeUnix]; 
        
        // ASCII码排序
        paramString.sort(); 

        // openid=abcd1s5a5ss&t=1318874398&key=131398
        let paramKey = paramString.join('&') + '&key=' + key;

        // MD5加密
        let encryptResult = MD5(paramKey).toUpperCase(); 

        // key=abcdefs&t=1318874398
        let requestQuery = 'key=' + encryptResult + '&t=' + timeUnix;

        return requestQuery;
    };
}
